package edu.chinasoft.servlet;

import edu.chinasoft.domain.User;
import edu.chinasoft.service.UserService;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@WebServlet(name = "myServletForLogin",value = "/servlet/servletforlogin")
public class ServletForLogin extends HttpServlet {
    private Logger logger = LoggerFactory.getLogger(ServletForLogin.class);
    private UserService userService;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        logger.debug("ServletForLogin>>>doPost start ……");
        //获取页面提交的内容
        String userName = request.getParameter("user_name");
        String userPassword = request.getParameter("user_password");
        //封装到javabean
        User user = new User();
        user.setUserName( userName );
        user.setUserPasswrod( userPassword );
        //初始化servelt里关于服务层方法成员变量
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        UserService userServiceImp = wac.getBean("userService",UserService.class);
        userService=userServiceImp;
        //调用服务层方法
        User loginUser = this.userService.loginUser( user );
        logger.debug("ServletForLogin>>>doPost end ……");
        if(loginUser==null){
            //根据执行结果实现页面跳转
            request.getRequestDispatcher("/login_fail.jsp").forward(request,response);
        }else {
            //把登录的用户保存到域里
            HttpSession session = request.getSession();
            session.setAttribute("user",loginUser);
            //跳转到主页面
            response.sendRedirect(""+request.getContextPath()+"/main.jsp");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}